#include "include/muduo/net/TcpClient.h"
#include "include/muduo/net/EventLoopThread.h"
#include "include/muduo/net/TcpConnection.h"
#include "include/muduo/base/CountDownLatch.h"

#include <iostream>
#include <functional>
#include <unordered_map>

class TranslateClient
{
public:
    TranslateClient(const std::string& sip, const int sport)
    : _latch(1), _client(_loopthread.startLoop(), muduo::net::InetAddress(sip, sport), "TrantlateClient")
    {
        _client.setConnectionCallback(std::bind(&TranslateClient::onConnect, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&TranslateClient::onMessage, this, std::placeholders::_1, 
        std::placeholders::_2, std::placeholders::_3));
    }
    void connect()
    {
        _client.connect();
        _latch.wait();
    }
    bool send(const std::string& msg)
    {
        if (_conn->connected() == true)
        {
            _conn->send(msg);
            return true;
        }
        return false;
    }
private:
    void onConnect(const muduo::net::TcpConnectionPtr& conn)
    {
        if (conn->connected() == true)
        {
            _conn = conn;
            _latch.countDown();
        }
        else
        {
            // 连接断开的情况
            _conn.reset();
        }
    }
    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp time)
    {
        std::cout << "翻译结果：" << buf->retrieveAllAsString() << std::endl;
    }
private:
    muduo::net::EventLoopThread _loopthread;
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _conn;
    muduo::CountDownLatch _latch;
};

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server-ip server-port" << std::endl;
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    TranslateClient client(serverip, serverport);
    client.connect();
    while (true)
    {
        std::string message;
        std::cin >> message;
        client.send(message);
    }

    return 0;
}